<script lang="ts" setup>
import { useTreeGui } from "@/hooks/use-tree-gui";
import { Background } from "@vue-flow/background";
import { Controls } from "@vue-flow/controls";
import { Panel, VueFlow, useVueFlow, type Elements } from "@vue-flow/core";
import { ref, watch } from "vue";
import { type TreeLike } from "@/models/tree-like";
import { randomTrees } from "./random-tree";

const props = withDefaults(defineProps<{ data: TreeLike[] }>(), { data: () => [] });
const emits = defineEmits<{ (event: "refresh", flat: TreeLike[]): void }>();
const dark = ref(false);
const elements = ref<Elements>([]);
const { onPaneReady, onNodeClick, fitView } = useVueFlow();

watch(
  () => props.data,
  (newVal) => {
    elements.value = useTreeGui(newVal).toElements();
  },
  { immediate: true },
);

onPaneReady(({ fitView }) => {
  fitView();
});

onNodeClick((param) => {
  console.log(param.node);
});

function resetTransform() {
  const flat = randomTrees(3, 4, 2);
  emits("refresh", flat);
}

function handleUpdate() {
  setTimeout(fitView, 0);
}
</script>

<template>
  <VueFlow
    v-model="elements"
    :class="{ dark }"
    class="basicflow"
    :default-viewport="{ zoom: 1 }"
    :min-zoom="0.2"
    :max-zoom="4"
    @update:model-value="handleUpdate"
  >
    <Background :pattern-color="dark ? '#FFFFFB' : '#aaa'" :gap="8" />
    <Controls />
    <Panel position="top-right" class="controls">
      <button style="background-color: #113285; color: white" title="Reset Transform" @click="resetTransform">
        <svg width="16" height="16" viewBox="0 0 32 32">
          <path fill="#FFFFFB" d="M18 28A12 12 0 1 0 6 16v6.2l-3.6-3.6L1 20l6 6l6-6l-1.4-1.4L8 22.2V16a10 10 0 1 1 10 10Z" />
        </svg>
      </button>
    </Panel>
  </VueFlow>
</template>

<style lang="scss" scoped>
.vue-flow {
  background: lightblue;
}
</style>
